package com.hua.filter;

import com.alibaba.fastjson.JSON;
import com.hua.common.BaseTool;
import com.hua.entities.Employee;
import com.hua.entities.R;
import com.hua.entities.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配对象，支持匹配通配符
    private final static AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();

        String [] urls = new String[]{
          "/employee/login",
          "/employee/logout",
           "/backend/**",
           "/front/**",
           "/user/sendMsg",
           "/user/login"
        };

        //静态资源过滤
        if(getFlage(urls,requestURI)){
            log.info("本次请求不需要处理");
            filterChain.doFilter(request,response);
            return;
        }

        //4-1
        //判断pc端是否登录，是的话放行
        if(request.getSession().getAttribute("user")!=null){
            Employee user = (Employee) request.getSession().getAttribute("user");
            log.info("用户名为:{}",user);
            BaseTool.setInfo(user.getId());
            filterChain.doFilter(request,response);
            return;
        }
        //4-2
        //判断移动端是否登录，是的话放行
        if(request.getSession().getAttribute("userPhone")!=null){
            User user = (User) request.getSession().getAttribute("userPhone");
            log.info("用户名为:{}",user);
            BaseTool.setInfo(user.getId());
            filterChain.doFilter(request,response);
            return;
        }

        log.info("用户没有登录");
        System.out.println(requestURI);
        //告诉浏览器我们没有登录
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }
    //判断路径是否是静态资源路径
    public boolean getFlage(String [] args,String url){
        for (int i = 0; i < args.length ; i++) {
            if(PATH_MATCHER.match(args[i],url)){
                return true;
            }
        }
        return false;
    }

}


